package nxu.it.controller;

import io.undertow.util.StatusCodes;

import nxu.it.dao.Impl.MemoryTodoStorage;
import nxu.it.dao.TodoStorage;
import nxu.it.model.Todo;
import org.noear.solon.annotation.Body;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Param;
import org.noear.solon.boot.web.MimeType;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.MethodType;
import org.noear.solon.core.handle.ModelAndView;

import java.util.*;
import java.util.stream.Stream;

@Controller
public class TodoController {
    static TodoStorage todoStorage = new MemoryTodoStorage();
    @Mapping(value = "/todo/list",method = MethodType.GET,produces = MimeType.TEXT_HTML_VALUE)
    public ModelAndView list() {
        ModelAndView mv = new ModelAndView("todo/list.ftl");
        mv.put("todoList",todoStorage.list());
        return mv;
    }
    @Mapping(value = "/todo/save",method = MethodType.POST,produces = MimeType.TEXT_HTML_VALUE)
    public void save(Context ctx,String content) {
        todoStorage.save(new Todo(content));
        ctx.redirect("/todo/list", StatusCodes.SEE_OTHER);
    }

    @Mapping(value = "/todo/check",method = MethodType.GET,produces = MimeType.TEXT_HTML_VALUE)
    public void check(Context ctx,int id) {
        todoStorage.check(id);
        ctx.redirect("/todo/list", StatusCodes.SEE_OTHER);
    }

    @Mapping(value = "/todo/edit",method = MethodType.GET,produces = MimeType.TEXT_HTML_VALUE)
    public ModelAndView edit(Context ctx,int id) {
        Optional<Todo> todoOpt = todoStorage.get(id);
        if(todoOpt.isEmpty()){
            return new ModelAndView("todo/not-found.ftl");
        }
        ModelAndView mv = new ModelAndView("todo/edit.ftl");
        mv.put("todo",todoOpt.get());
        return mv;
    }

    @Mapping(value = "/todo/update",method = MethodType.POST,produces = MimeType.TEXT_HTML_VALUE)
    public void update(Context ctx,Todo todo) {
        todoStorage.update(todo);
        ctx.redirect("/todo/list", StatusCodes.SEE_OTHER);
    }
    @Mapping(value = "/todo/delete",method = MethodType.GET,produces = MimeType.TEXT_HTML_VALUE)
    public void delete(Context ctx,int id) {
        todoStorage.delete(id);
        ctx.redirect("/todo/list", StatusCodes.SEE_OTHER);
    }

}
